package cn.edu.gznu.wecampus.core.auth;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.gznu.wecampus.core.common.entity.jpa.Role;
import cn.edu.gznu.wecampus.core.common.entity.jpa.User;
import cn.edu.gznu.wecampus.core.common.repository.jpa.RolePermissionRepository;
import cn.edu.gznu.wecampus.core.common.repository.jpa.UserRepository;
import cn.edu.gznu.wecampus.core.common.repository.jpa.UserRoleRepository;
import cn.edu.gznu.wecampus.core.web.RestResponse;
import cn.edu.gznu.wecampus.core.web.RestResponseElement;
import cn.edu.gznu.wecampus.core.web.annotation.CurrentUser;
import lombok.Getter;
import lombok.Setter;

@RestController
@RequestMapping("/api/userInfo")
public class UserInfoApi {
	
	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private UserRoleRepository userRoleRepository;
	
	@Autowired
	private RolePermissionRepository rolePermissionRepository;

	@GetMapping("get")
	public RestResponse get(@CurrentUser String userId) {
		User user = userRepository.findByUsername(userId);
		List<Role> roles = userRoleRepository.findByUser(user).stream()
			.map(userRole -> userRole.getRole())
			.collect(Collectors.toList());
		List<String> permissionIds = new LinkedList<String>();
		roles.forEach(role -> {
			permissionIds.addAll(
				rolePermissionRepository.findByRole(role).stream()
					.map(rolePermission -> rolePermission.getPermission())
					.collect(Collectors.toList())
			);
		});
		UserInfoVo userInfo = new UserInfoVo();
		userInfo.setUserId(userId);
		userInfo.setPermissionIds(permissionIds.stream().distinct().collect(Collectors.toList()));
		RestResponseElement response = new RestResponseElement();
		response.setElement(userInfo);
		return response;
	}
	
	@Getter
	@Setter
	public static class UserInfoVo {
		private String userId;
		private List<String> permissionIds = new LinkedList<String>();
	}
}
